package com.megvii.koala.tv.video;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;

import com.megvii.corelib.util.MegviiToast;
import com.megvii.koala.constance.ErrorCode;

import java.io.IOException;

/**
 * Created by linyue on 16/3/14.
 */
public class VideoManagerEx implements VideoManagerInterface
{
    private Window window;

    private SurfaceView surfaceView;

    private SurfaceHolder surfaceHolder;

    private MediaPlayer mediaPlayer;

    private Object mediaPlayerLock;

    private String url;

    private boolean isLocalFile = false;

    private Thread fixingThread;

    private Handler handler = null;

    private VideoManagerListener listener;

    @Override
    public boolean init(final Window window, SurfaceView surfaceView)
    {
        this.window = window;
        this.surfaceView = surfaceView;
        this.handler = new Handler(Looper.getMainLooper());
        mediaPlayerLock = new Object();
        createFixThread();
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(new SurfaceHolder.Callback()
        {
            @Override
            public void surfaceCreated(SurfaceHolder holder)
            {
                synchronized (mediaPlayerLock)
                {
                    if (mediaPlayer != null)
                    {
                        mediaPlayer.setDisplay(surfaceHolder);
                    }
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
            {
                synchronized (mediaPlayerLock)
                {
                    if (mediaPlayer != null)
                    {
                        mediaPlayer.setDisplay(surfaceHolder);
                    }
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder)
            {

            }
        });
        return true;
    }

    @Override
    public void release()
    {
        listener = null;
        if (fixingThread != null)
        {
            fixingThread.interrupt();
            try
            {
                fixingThread.join();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        fixingThread = null;
        destroyMediaPlayer();
    }

    @Override
    public void restartPlay()
    {
        synchronized (mediaPlayerLock)
        {
            if (url != null)
            {
                recreateMediaPlayer();
                try
                {
                    if (url.startsWith("/"))
                    {
                        isLocalFile = true;
                    }
                    else
                    {
                        if (url.indexOf("rtspt") != -1) {
                            //TCP模式的
                            url = url.replace("rtspt", "rtsp");
                        }
                        isLocalFile = false;
                    }
                    Uri uri = Uri.parse(url);
                    mediaPlayer.setDataSource(window.getContext(), uri);
                    mediaPlayer.prepareAsync();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void play(String url)
    {
        synchronized (mediaPlayerLock)
        {
            this.url = url;
            restartPlay();
        }
    }

    @Override
    public void clearSrc()
    {
        synchronized (mediaPlayerLock)
        {
            this.url = null;
        }
    }

    @Override
    public void stop()
    {
        destroyMediaPlayer();
    }

    @Override
    public void setSize(int width, int height)
    {

    }

    @Override
    public int getVideoCurrentTime()
    {
        synchronized (mediaPlayerLock)
        {
            if (false && mediaPlayer != null)
            {
                return mediaPlayer.getCurrentPosition();
            }
            else
            {
                return -1;
            }
        }
    }

    @Override
    public int getVideoDuration()
    {
        synchronized (mediaPlayerLock)
        {
            if (false && mediaPlayer != null)
            {
                return mediaPlayer.getDuration();
            }
            else
            {
                return -1;
            }
        }
    }

    @Override
    public void setListener(VideoManagerListener listener)
    {
        this.listener = listener;
    }

    private void createMediaPlayer()
    {
        synchronized (mediaPlayerLock)
        {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener()
            {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra)
                {
                    if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN || what == -10102 || what == -10103)
                    {
                        if (isLocalFile)
                        {
                            handler.post(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    if (listener != null)
                                    {
                                        listener.onVideoError(ErrorCode.CANNOT_PLAY_VIDEO);
                                    }
                                }
                            });
                        }
                    }
                    else
                    {
                        MegviiToast.showToast(window.getContext(),
                                "OnMediaPlayerError what:" + what + " extra: " + extra);
                    }
                    return true;
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
            {
                @Override
                public void onCompletion(MediaPlayer mp)
                {
                    restartPlay();
                }
            });
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
            {
                @Override
                public void onPrepared(MediaPlayer mp)
                {
                    mediaPlayer.start();
                }
            });
            if (surfaceHolder.getSurface().isValid())
            {
                mediaPlayer.setDisplay(surfaceHolder);
            }
        }
    }

    private void createFixThread()
    {
        fixingThread = new Thread()
        {
            public void run()
            {
                try
                {
                    while (!interrupted())
                    {
                        sleep(10 * 60 * 1000);
                        restartPlay();
                    }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        };
        fixingThread.start();
    }

    private void destroyMediaPlayer()
    {
        synchronized (mediaPlayerLock)
        {
            if (mediaPlayer != null)
            {
                mediaPlayer.setOnPreparedListener(null);
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    }

    private void recreateMediaPlayer()
    {
        synchronized (mediaPlayerLock)
        {
            destroyMediaPlayer();
            createMediaPlayer();
        }
    }
}
